package gestioneDatabase.Post;

import gestioneDatabase.MultipleDatabaseElementUser;


import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import models.Post;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 * Permette l'inserimento di una riposta in un post.
 *
 */

public class ResponseInserter extends MultipleDatabaseElementUser {

	private Post responseToInsert;
	private int postID;
	private ResponseInserterFiller filler = new ResponseInserterFiller();

	public ResponseInserter(Post responseToInsert, int postID) {
		super();
		this.responseToInsert = responseToInsert;
		this.postID = postID;
	}

	@Override
	public void execute() {

		try {

			NodeList nList = open("DatabasePost", "Post");

			for (int i = 0; i < nList.getLength(); i++) {

				Node nNode = nList.item(i);

				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;

					if (Integer.parseInt(eElement.getAttribute("id")) == postID) {
						int n = Integer.parseInt(eElement
								.getElementsByTagName("ResponseNumber").item(0)
								.getTextContent());
						filler.fill(responseToInsert, eElement, n, doc);
					}
				}
			}
			controller.writeIntoXMLFile(filepath);

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (TransformerException tfe) {
			tfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (SAXException sae) {
			sae.printStackTrace();
		}
	}
}
